// 显示Toast提示的函数
function showToast(message, duration = 3000) {
    const toast = document.getElementById('toast');
    toast.textContent = message;
    toast.classList.add('show');

    // 设置延迟后自动关闭
    setTimeout(() => {
        toast.classList.remove('show');
    }, duration);
}

// 监听来自background的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === "showResult") {
        if (request.success) {
            // 显示成功结果
            showToast('验证成功，点击"查看结果"按钮查看详情');

            // 保存结果数据，以便查看
            chrome.storage.local.set({
                'lastCheckResult': {
                    success: true,
                    data: request.data,
                    timestamp: new Date().toISOString()
                }
            });
        } else {
            // 显示错误信息
            showToast('验证失败: ' + request.error);
        }
    }
});

// 选中的书签和文件夹ID
let selectedItems = [];

// 加载书签树
function loadBookmarkTree() {
    const treeContainer = document.getElementById('bookmarkTree');

    chrome.bookmarks.getTree((bookmarkTree) => {
        // 清空容器
        treeContainer.innerHTML = '';

        // 渲染书签树
        bookmarkTree.forEach(root => {
            renderBookmarkNode(root, treeContainer);
        });

        // 加载保存的选择
        loadSelectedItems();
    });
}

// 渲染书签节点
function renderBookmarkNode(node, container) {
    const nodeElement = document.createElement('div');
    nodeElement.className = 'tree-node';
    nodeElement.dataset.id = node.id;

    const contentElement = document.createElement('div');
    contentElement.className = 'tree-content';

    // 添加复选框
    const checkbox = document.createElement('input');
    checkbox.type = 'checkbox';
    checkbox.className = 'tree-checkbox';
    checkbox.dataset.id = node.id;
    checkbox.addEventListener('change', function() {
        toggleSelection(node.id, this.checked);
    });
    contentElement.appendChild(checkbox);

    // 如果有子节点，添加展开/折叠按钮
    if (node.children && node.children.length > 0) {
        const toggleElement = document.createElement('span');
        toggleElement.className = 'tree-toggle';
        toggleElement.textContent = '▶';
        toggleElement.addEventListener('click', function() {
            toggleNode(nodeElement);
        });
        contentElement.appendChild(toggleElement);
    } else {
        // 添加空白占位
        const spacer = document.createElement('span');
        spacer.className = 'tree-toggle';
        spacer.innerHTML = '&nbsp;';
        contentElement.appendChild(spacer);
    }

    // 添加标签
    const labelElement = document.createElement('span');
    labelElement.className = 'tree-label';
    labelElement.textContent = node.title || '(无标题)';

    // 区分文件夹和书签
    if (node.children) {
        labelElement.classList.add('tree-folder');
    } else if (node.url) {
        labelElement.classList.add('tree-bookmark');
        labelElement.title = node.url;
    }

    labelElement.addEventListener('click', function() {
        checkbox.checked = !checkbox.checked;
        toggleSelection(node.id, checkbox.checked);
    });

    contentElement.appendChild(labelElement);
    nodeElement.appendChild(contentElement);

    // 如果有子节点，递归渲染
    if (node.children && node.children.length > 0) {
        const childrenContainer = document.createElement('div');
        childrenContainer.className = 'tree-children';

        node.children.forEach(child => {
            renderBookmarkNode(child, childrenContainer);
        });

        nodeElement.appendChild(childrenContainer);
    }

    container.appendChild(nodeElement);
}

// 展开/折叠节点
function toggleNode(nodeElement) {
    const isExpanded = nodeElement.classList.contains('tree-expanded');
    const toggleElement = nodeElement.querySelector('.tree-toggle');

    if (isExpanded) {
        nodeElement.classList.remove('tree-expanded');
        toggleElement.textContent = '▶';
    } else {
        nodeElement.classList.add('tree-expanded');
        toggleElement.textContent = '▼';
    }
}

// 切换选择状态
function toggleSelection(id, isSelected) {
    // 获取当前节点元素
    const nodeElement = document.querySelector(`.tree-node[data-id="${id}"]`);

    if (isSelected) {
        // 添加当前节点到选中列表
        if (!selectedItems.includes(id)) {
            selectedItems.push(id);
        }

        // 如果是文件夹，递归选中所有子节点
        if (nodeElement) {
            const childCheckboxes = nodeElement.querySelectorAll('.tree-checkbox');
            childCheckboxes.forEach(checkbox => {
                checkbox.checked = true;
                const childId = checkbox.dataset.id;
                if (!selectedItems.includes(childId)) {
                    selectedItems.push(childId);
                }
            });
        }
    } else {
        // 移除当前节点
        selectedItems = selectedItems.filter(item => item !== id);

        // 如果是文件夹，递归取消选中所有子节点
        if (nodeElement) {
            const childCheckboxes = nodeElement.querySelectorAll('.tree-checkbox');
            childCheckboxes.forEach(checkbox => {
                checkbox.checked = false;
                const childId = checkbox.dataset.id;
                selectedItems = selectedItems.filter(item => item !== childId);
            });
        }
    }

    // 保存选择
    saveSelectedItems();
}

// 保存选中的项目
function saveSelectedItems() {
    chrome.storage.local.set({ 'excludeItems': selectedItems }, () => {
        console.log('排除项已保存:', selectedItems);
    });
}

// 加载保存的选择
function loadSelectedItems() {
    chrome.storage.local.get('excludeItems', (result) => {
        if (result.excludeItems && Array.isArray(result.excludeItems)) {
            selectedItems = result.excludeItems;

            // 更新复选框状态
            selectedItems.forEach(id => {
                const checkbox = document.querySelector(`.tree-checkbox[data-id="${id}"]`);
                if (checkbox) {
                    checkbox.checked = true;

                    // 展开父节点
                    let parent = checkbox.closest('.tree-node');
                    while (parent) {
                        parent.classList.add('tree-expanded');
                        const toggle = parent.querySelector('.tree-toggle');
                        if (toggle) toggle.textContent = '▼';
                        parent = parent.parentElement.closest('.tree-node');
                    }
                }
            });
        }
    });
}

// 页面加载时检查是否有上次的结果
document.addEventListener('DOMContentLoaded', () => {
    // 加载书签树
    loadBookmarkTree();
});

// 渲染结果树
function renderResultTree(resultData) {
    try {
        const resultContainer = document.getElementById('resultTree');
        resultContainer.innerHTML = '';
        console.log(resultData)
        if (!resultData || typeof resultData !== 'object') {
            const errorNode = document.createElement('div');
            errorNode.textContent = '无有效结果数据';
            errorNode.style.color = '#ea4335';
            resultContainer.appendChild(errorNode);
            return;
        }

        // 限制数据大小，防止渲染过大的数据导致浏览器崩溃
        const maxDepth = 5; // 最大递归深度
        const maxChildren = 50; // 每个节点最大子节点数

    // 递归创建结果树
    function createResultNode(key, value, depth = 0) {
        // 限制递归深度
        if (depth > maxDepth) {
            const nodeElement = document.createElement('div');
            nodeElement.className = 'tree-node';
            const contentElement = document.createElement('div');
            contentElement.className = 'tree-content';
            const labelElement = document.createElement('span');
            labelElement.className = 'tree-label';
            labelElement.textContent = `${key}: [达到最大深度限制]`;
            labelElement.style.color = '#fbbc05';
            contentElement.appendChild(labelElement);
            nodeElement.appendChild(contentElement);
            return nodeElement;
        }

        const nodeElement = document.createElement('div');
        nodeElement.className = 'tree-node';

        const contentElement = document.createElement('div');
        contentElement.className = 'tree-content';

        // 如果是对象或数组，添加展开/折叠按钮
        if (value !== null && typeof value === 'object') {
            const toggleElement = document.createElement('span');
            toggleElement.className = 'tree-toggle';
            toggleElement.textContent = '▶';
            toggleElement.addEventListener('click', function() {
                toggleNode(nodeElement);
            });
            contentElement.appendChild(toggleElement);
        } else {
            // 添加空白占位
            const spacer = document.createElement('span');
            spacer.className = 'tree-toggle';
            spacer.innerHTML = '&nbsp;';
            contentElement.appendChild(spacer);
        }

        // 添加标签
        const labelElement = document.createElement('span');
        labelElement.className = 'tree-label';

        // 根据值的类型设置不同的样式
        if (value === null) {
            labelElement.textContent = `${key}: null`;
        } else if (typeof value === 'object') {
            labelElement.textContent = `${key}: ${Array.isArray(value) ? value.length : value.url}`;
            labelElement.classList.add('tree-folder');
        } else {
            // 根据值的内容添加不同的样式
            if (typeof value === 'boolean') {
                labelElement.classList.add(value ? 'result-valid' : 'result-invalid');
            } else if (typeof value === 'string' && (value.includes('error') || value.includes('失败'))) {
                labelElement.classList.add('result-invalid');
            } else if (typeof value === 'string' && (value.includes('success') || value.includes('成功'))) {
                labelElement.classList.add('result-valid');
            } else if (typeof value === 'string' && value.includes('warning')) {
                labelElement.classList.add('result-warning');
            }

            // 限制字符串长度，防止过长导致页面卡顿
            const displayValue = typeof value === 'string' && value.length > 500
                ? value.substring(0, 500) + '...'
                : value;

            labelElement.textContent = `${key}: ${displayValue}`;
        }

        contentElement.appendChild(labelElement);
        nodeElement.appendChild(contentElement);

        // 如果是对象或数组，递归处理子节点
        if (value !== null && typeof value === 'object') {
            const childrenContainer = document.createElement('div');
            childrenContainer.className = 'tree-children';

            try {
                if (Array.isArray(value)) {
                    // 限制数组子节点数量
                    const limitedArray = value.slice(0, maxChildren);
                    limitedArray.forEach((item, index) => {
                        const childNode = createResultNode(`[${index}]`, item, depth + 1);
                        childrenContainer.appendChild(childNode);
                    });

                    // 如果有更多项，显示提示
                    if (value.length > maxChildren) {
                        const moreNode = document.createElement('div');
                        moreNode.className = 'tree-node';
                        moreNode.innerHTML = `<div class="tree-content"><span class="tree-label" style="color:#fbbc05">...还有${value.length - maxChildren}项未显示</span></div>`;
                        childrenContainer.appendChild(moreNode);
                    }
                } else {
                    // 限制对象子节点数量
                    const keys = Object.keys(value);
                    const limitedKeys = keys.slice(0, maxChildren);

                    limitedKeys.forEach(childKey => {
                        const childNode = createResultNode(childKey, value[childKey], depth + 1);
                        childrenContainer.appendChild(childNode);
                    });

                    // 如果有更多项，显示提示
                    if (keys.length > maxChildren) {
                        const moreNode = document.createElement('div');
                        moreNode.className = 'tree-node';
                        moreNode.innerHTML = `<div class="tree-content"><span class="tree-label" style="color:#fbbc05">...还有${keys.length - maxChildren}项未显示</span></div>`;
                        childrenContainer.appendChild(moreNode);
                    }
                }
            } catch (error) {
                const errorNode = document.createElement('div');
                errorNode.className = 'tree-node';
                errorNode.innerHTML = `<div class="tree-content"><span class="tree-label result-invalid">处理子节点时出错: ${error.message}</span></div>`;
                childrenContainer.appendChild(errorNode);
            }

            nodeElement.appendChild(childrenContainer);
        }

        return nodeElement;
    }

    // 创建根节点
    Object.keys(resultData).forEach(key => {
        const rootNode = createResultNode(key, resultData[key]);
        resultContainer.appendChild(rootNode);
    });
} catch (error) {
    console.error('渲染结果树时出错:', error);
    const resultContainer = document.getElementById('resultTree');
    resultContainer.innerHTML = '';
    const errorNode = document.createElement('div');
    errorNode.textContent = '渲染结果时出错: ' + error.message;
    errorNode.style.color = '#ea4335';
    resultContainer.appendChild(errorNode);
}
}

// 切换视图（书签选择/结果显示）
function toggleView(showResult) {
    const bookmarkSection = document.getElementById('bookmarkSection');
    const resultSection = document.getElementById('resultSection');
    const resultTree = document.getElementById('resultTree');
    const backBtn = document.getElementById('backBtn');
    const exportBtn = document.getElementById('exportBtn');

    if (showResult) {
        bookmarkSection.style.display = 'none';
        resultSection.style.display = 'flex';
        resultTree.style.display = 'block'; // 确保结果树显示
        backBtn.style.display = 'block';
        exportBtn.style.display = 'none';
    } else {
        bookmarkSection.style.display = 'flex';
        resultSection.style.display = 'none';
        backBtn.style.display = 'none';
        exportBtn.style.display = 'block';
    }
}

// 计算结果总数
function countResultItems(data) {
    let count = 0;

    // 直接计算数组长度
    function countArrayItems(obj) {
        if (!obj || typeof obj !== 'object') return 0;

        let itemCount = 0;

        if (Array.isArray(obj)) {
            // 直接使用数组长度
            itemCount += obj.length;

            // 如果数组中还有数组，继续计算
            obj.forEach(item => {
                if (item && typeof item === 'object' && Array.isArray(item)) {
                    itemCount += countArrayItems(item);
                }
            });
        } else {
            // 对象中查找数组属性
            Object.values(obj).forEach(value => {
                if (value && typeof value === 'object') {
                    if (Array.isArray(value)) {
                        itemCount += value.length;

                        // 继续检查数组中的数组
                        value.forEach(item => {
                            if (item && typeof item === 'object' && Array.isArray(item)) {
                                itemCount += countArrayItems(item);
                            }
                        });
                    } else {
                        // 递归检查对象中的数组
                        itemCount += countArrayItems(value);
                    }
                }
            });
        }

        return itemCount;
    }

    return countArrayItems(data);
}

// 查看结果按钮点击事件
document.getElementById('viewResultBtn').addEventListener('click', () => {
    try {
        chrome.storage.local.get('lastCheckResult', (result) => {
            try {
                if (result && result.lastCheckResult && result.lastCheckResult.data) {
                    const resultData = result.lastCheckResult.data;
                    const totalCount = countResultItems(resultData);

                    // 更新结果标签，显示总数
                    const resultLabel = document.querySelector('#resultSection label');
                    resultLabel.textContent = `验证结果：(总共有 ${totalCount} 个可能失效的书签地址哦~)`;

                    renderResultTree(resultData);
                    toggleView(true);
                } else {
                    showToast('没有可用的验证结果');
                }
            } catch (error) {
                console.error('处理结果数据时出错:', error);
                showToast('处理结果数据时出错: ' + error.message);
            }
        });
    } catch (error) {
        console.error('获取结果数据时出错:', error);
        showToast('获取结果数据时出错: ' + error.message);
    }
});

// 返回按钮点击事件
document.getElementById('backBtn').addEventListener('click', () => {
    toggleView(false);
});

document.getElementById('exportBtn').addEventListener('click', () => {
    // 显示美观的提示信息
    showToast('验证过程可能需要1-5分钟，验证结果将在稍后提醒');

    // 发送消息给background，包含排除项
    chrome.runtime.sendMessage({
        action: "exportBookmarks",
        excludeItems: selectedItems
    });

    // 不要立即关闭窗口，等待结果返回
});
